posterior_trees <- sample(posterior_trees, size = n_trees)
posterior_trees <-lapply(posterior_trees, ladderize, right=TRUE) #ladderizes trees
#write.nexus(posterior_trees, file = paste(n_trees,"_posterior_trees.nex", sep="")) #in case you want the unpruned trees
pruned_trees <- lapply(posterior_trees, keep.tip, tip=species) #drops unwanted tips (outgroups, etc)
class(pruned_trees) <- "multiPhylo"
for(i in 1:length(pruned_trees)) {
tree <- pruned_trees[[i]]
if(is.binary(tree)){} else{
#resolves polytomies and zero-length branches
tree <- multi2di(tree, random = TRUE)
tree$edge.length[tree$edge.length==0]<-1e-8
pruned_trees[[i]] <- tree
n_polytomous <- n_polytomous+1
}
# imposes minimum branch lengths for BioGeoBEARS
# this might be necessary in some trees with sampled fossils where the fossil edge lengths are too short
# in these cases you get the error "FATAL ERROR in check_BioGeoBEARS_run(): the input tree has branchlengths <= 0, at these nodes:..."
# this might fix this but is not necessary in most cases
if(fossil_tips){
tree <- impose_min_brlen(tree)
height <- round(max(nodeHeights(tree)),1)
for (a in 1:length(species)){
if((round(nodeheight(tree, a),1))==height) next #checks if tip is a fossil
if(tree$edge.length[which(tree$edge[,2]==a)] < 0.1) tree$edge.length[which(tree$edge[,2]==a)] <- 0.1 #if its branch length is smaller than 0.1, correct this for BioGeoBEARS
print(paste("Corrected branch length of taxon ",a," in tree ",i,sep=""))
}
}
#writes trees to individual files
write.tree(tree, file = paste(dir_name, "/trees/tree",i,".nex", sep= ""))
}
}
print(paste("Polytomous trees forcibly resolved:",n_polytomous)) #checks the number of trees forcibly resolved, usually this is 0
write.nexus(pruned_trees, file = paste(dir_name, "/trees/",n_trees,"_pruned_trees.nex", sep= "")) #all the trees in a single file
toc()
# samples the trees from a posterior distribution
# do NOT sample trees again if you plan to load previous results of BioGeoBEARS estimates!
if (sample_trees==TRUE & run_BGB == TRUE) {
tic()
posterior_trees <- read.nexus(posterior_trees_fn)
n_polytomous <- 0
if(n_trees == 1) { # if this is a single target tree...
posterior_trees <- ladderize(posterior_trees, right=TRUE)
pruned_trees <- keep.tip(posterior_trees, tip=species)
if(is.binary(pruned_trees)){} else{
#resolves polytomies and zero-length branches
pruned_trees <- multi2di(pruned_trees, random = TRUE)
pruned_trees$edge.length[pruned_trees$edge.length==0]<-1e-8
pruned_trees[[i]] <- pruned_trees
n_polytomous <- n_polytomous+1
}
write.tree(pruned_trees, file = paste(dir_name, "/trees/tree",1,".nex", sep= ""))
} else { # if this is a distribution of trees...
class(posterior_trees) <- "multiPhylo"
#samples N trees from the posterior distribution
posterior_trees <- sample(posterior_trees, size = n_trees)
posterior_trees <-lapply(posterior_trees, ladderize, right=TRUE) #ladderizes trees
#write.nexus(posterior_trees, file = paste(n_trees,"_posterior_trees.nex", sep="")) #in case you want the unpruned trees
pruned_trees <- lapply(posterior_trees, keep.tip, tip=species) #drops unwanted tips (outgroups, etc)
class(pruned_trees) <- "multiPhylo"
for(i in 1:length(pruned_trees)) {
tree <- pruned_trees[[i]]
if(is.binary(tree)){} else{
#resolves polytomies and zero-length branches
tree <- multi2di(tree, random = TRUE)
tree$edge.length[tree$edge.length==0]<-1e-8
pruned_trees[[i]] <- tree
n_polytomous <- n_polytomous+1
}
# imposes minimum branch lengths for BioGeoBEARS
# this might be necessary in some trees with sampled fossils where the fossil edge lengths are too short
# in these cases you get the error "FATAL ERROR in check_BioGeoBEARS_run(): the input tree has branchlengths <= 0, at these nodes:..."
# this might fix this but is not necessary in most cases
if(fossil_tips){
tree <- impose_min_brlen(tree)
height <- round(max(nodeHeights(tree)),1)
for (a in 1:length(species)){
if((round(nodeheight(tree, a),1))==height) next #checks if tip is a fossil
if(tree$edge.length[which(tree$edge[,2]==a)] < 0.1) tree$edge.length[which(tree$edge[,2]==a)] <- 0.1 #if its branch length is smaller than 0.1, correct this for BioGeoBEARS
print(paste("Corrected branch length of taxon ",a," in tree ",i,sep=""))
}
}
#writes trees to individual files
write.tree(tree, file = paste(dir_name, "/trees/tree",i,".nex", sep= ""))
}
}
print(paste("Polytomous trees forcibly resolved:",n_polytomous)) #checks the number of trees forcibly resolved, usually this is 0
write.nexus(pruned_trees, file = paste(dir_name, "/trees/",n_trees,"_pruned_trees.nex", sep= "")) #all the trees in a single file
toc()
}
# get the list of state names
statenames = areas_list_to_states_list_new(getareas_from_tipranges_object(tipranges))
statelabels = vector(length=num_states)
# get only labels for possible ranges (disconsiders ranges including more areas than max_range_size)
for (a in 1:num_states){statelabels[[a]] <- paste(statenames[[a]], collapse="")}
# settings for plotting results of the stochastic maps
states_list_0based = rcpp_areas_list_to_states_list(areas=areas, maxareas=max_range_size, include_null_range=TRUE)
colors_list_for_states = get_colors_for_states_list_0based(areanames=areas, states_list_0based=states_list_0based, max_range_size=max_range_size, plot_null_range=TRUE)
# gets the number of edges
trfn <- paste(dir_name, "/trees/tree",1,".nex", sep= "")
tr <- read.tree(trfn)
#writes trees to individual files
write.tree(tree, file = paste("/trees/tree",i,".nex", sep= ""))
#writes trees to individual files
write.tree(tree, file = paste(wd, "/trees/tree",i,".nex", sep= ""))
#writes trees to individual files
write.tree(tree, file = paste(results_object, "/trees/tree",i,".nex", sep= ""))
#writes trees to individual files
write.tree(tree, file = paste(dir_name))
# get the list of state names
statenames = areas_list_to_states_list_new(getareas_from_tipranges_object(tipranges))
statelabels = vector(length=num_states)
# get only labels for possible ranges (disconsiders ranges including more areas than max_range_size)
for (a in 1:num_states){statelabels[[a]] <- paste(statenames[[a]], collapse="")}
# settings for plotting results of the stochastic maps
states_list_0based = rcpp_areas_list_to_states_list(areas=areas, maxareas=max_range_size, include_null_range=TRUE)
colors_list_for_states = get_colors_for_states_list_0based(areanames=areas, states_list_0based=states_list_0based, max_range_size=max_range_size, plot_null_range=TRUE)
# gets the number of edges
trfn <- paste(dir_name, "/trees/tree",1,".nex", sep= "")
tr <- read.tree(trfn)
ingroup <- drop.tip(tr, tip = outgroup_taxa)
n_edges <- length(ingroup$edge[,1])
if(length(tr$tip.label) > length(ingroup$tip.label)) n_edges <- n_edges+1 # if outgroups are skipped, we still want the ancestral node of the ingroup to be counted
tMax_allreps = 0
# make a list of vectors to place the transitions by replicate and edge
# this prints the identify of the ancestor and descendant nodes,
# the distribution range of each of them,
# the transition ("A -> AB"), if any,
# and the most likely time of the transition, weighted by probabilities at each node
ColumnLenght =n_trees*(n_edges)*n_stochastic_maps
BSM_transitions = list(
replicate= c(rep(0, ColumnLenght)),
BSMreplicate= c(rep(0, ColumnLenght)),
nodeStart= c(rep(0, ColumnLenght)),
nodeEnd= c(rep(0, ColumnLenght)),
nodeEndLabel= c(rep("", ColumnLenght)),
ageStart= c(rep(0, ColumnLenght)),
ageEnd= c(rep(0, ColumnLenght)),
rangeAncestor= c(rep("", ColumnLenght)),
rangeStart= c(rep("", ColumnLenght)),
rangeEnd= c(rep("", ColumnLenght)),
transitionCladog= c(rep("", ColumnLenght)),
transitionCladogType= c(rep("", ColumnLenght)),
transitionAnag= c(rep("", ColumnLenght)),
transitionAnagType= c(rep("", ColumnLenght)),
transitionTime= c(rep(0, ColumnLenght)),
nodeOfInterest= c(rep("", ColumnLenght)),
BGBeventTypeClado= c(rep("", ColumnLenght)),
BGBeventTypeAnag= c(rep("", ColumnLenght))
)
counter = 1 # this counter will be used to populate the BSM_transitions table
# make a matrix to store lineages per area per time slice
CountStatesByTime_all_reps = matrix(NA, ncol = (length(statelabels)+4+num_areas), nrow = 0)
names_single_areas <- vector(length = num_areas)
for(i in 1:num_areas){names_single_areas[[i]] <- paste("SUM_",statelabels[[i+1]],sep="")}
colnames(CountStatesByTime_all_reps) = c("TimePoint","replication","BSM",statelabels, "LTT", names_single_areas)
# event names
n_insituesp <- "in_situ_speciation"
n_foundesp <- "founder_event_speciation"
n_vicsubsym <- "vicariance_or_subset_sympatry" # we will distinguish these events later by looking at both descendants
n_widesym_subsym <- "wide_sympatry_or_subset_sympatry" # we will distinguish these events later by looking at both descendants
n_vic <- "allopatry"
n_subsym <- "subset_sympatry"
n_dispersal <- "dispersal"
n_extinction <- "extinction"
n_disp_ext <- "dispersal_and_extinction"
n_impos_event <- "X"
no_event <- "–"
# make a matrix to store general statistics of the trees
transition_types <- c(n_insituesp, n_foundesp, n_vic, n_subsym, n_dispersal, n_extinction)
transition_types_mean <-lapply(transition_types, paste, "_mean", sep="")
transition_types_SD <-lapply(transition_types, paste, "_SD", sep="")
ReplicationParameters = matrix(0, ncol = 10+(2*length(transition_types)), nrow = n_trees)
colnames(ReplicationParameters) <- c("replication", "log-likelihood", "AICc", "k", "n_taxa", "d", "e", "j", "w", "treeHeight", transition_types_mean, transition_types_SD)
# make matrices to count the number of transitions between states
# template for event tables of each replication
state_by_state_transitions_template = matrix(0, ncol = length(statelabels), nrow = length(statelabels))
colnames(state_by_state_transitions_template) = statelabels
rownames(state_by_state_transitions_template) = statelabels
# a function by Liam Revell to get node numbers for descendants of a particular node. Thanks Liam!
getDescendants<-function(tree,node,curr=NULL){
if(is.null(curr)) curr<-vector()
daughters<-tree$edge[which(tree$edge[,1]==node),2]
curr<-c(curr,daughters)
w<-which(daughters>=length(tree$tip))
if(length(w)>0) for(i in 1:length(w))
curr<-getDescendants(tree,daughters[w[i]],curr)
return(curr)
# a function by Liam Revell to get node numbers for descendants of a particular node. Thanks Liam!
getDescendants<-function(tree,node,curr=NULL){
if(is.null(curr)) curr<-vector()
daughters<-tree$edge[which(tree$edge[,1]==node),2]
curr<-c(curr,daughters)
w<-which(daughters>=length(tree$tip))
if(length(w)>0) for(i in 1:length(w))
curr<-getDescendants(tree,daughters[w[i]],curr)
return(curr)
}
# get the list of state names
statenames = areas_list_to_states_list_new(getareas_from_tipranges_object(tipranges))
statelabels = vector(length=num_states)
# get only labels for possible ranges (disconsiders ranges including more areas than max_range_size)
for (a in 1:num_states){statelabels[[a]] <- paste(statenames[[a]], collapse="")}
# settings for plotting results of the stochastic maps
states_list_0based = rcpp_areas_list_to_states_list(areas=areas, maxareas=max_range_size, include_null_range=TRUE)
colors_list_for_states = get_colors_for_states_list_0based(areanames=areas, states_list_0based=states_list_0based, max_range_size=max_range_size, plot_null_range=TRUE)
# gets the number of edges
trfn <- paste(dir_name, "/trees/tree",1,".nex", sep= "")
tr <- read.tree(trfn)
ingroup <- drop.tip(tr, tip = outgroup_taxa)
n_edges <- length(ingroup$edge[,1])
if(length(tr$tip.label) > length(ingroup$tip.label)) n_edges <- n_edges+1 # if outgroups are skipped, we still want the ancestral node of the ingroup to be counted
tMax_allreps = 0
# make a list of vectors to place the transitions by replicate and edge
# this prints the identify of the ancestor and descendant nodes,
# the distribution range of each of them,
# the transition ("A -> AB"), if any,
# and the most likely time of the transition, weighted by probabilities at each node
ColumnLenght =n_trees*(n_edges)*n_stochastic_maps
BSM_transitions = list(
replicate= c(rep(0, ColumnLenght)),
BSMreplicate= c(rep(0, ColumnLenght)),
nodeStart= c(rep(0, ColumnLenght)),
nodeEnd= c(rep(0, ColumnLenght)),
nodeEndLabel= c(rep("", ColumnLenght)),
ageStart= c(rep(0, ColumnLenght)),
ageEnd= c(rep(0, ColumnLenght)),
rangeAncestor= c(rep("", ColumnLenght)),
rangeStart= c(rep("", ColumnLenght)),
rangeEnd= c(rep("", ColumnLenght)),
transitionCladog= c(rep("", ColumnLenght)),
transitionCladogType= c(rep("", ColumnLenght)),
transitionAnag= c(rep("", ColumnLenght)),
transitionAnagType= c(rep("", ColumnLenght)),
transitionTime= c(rep(0, ColumnLenght)),
nodeOfInterest= c(rep("", ColumnLenght)),
BGBeventTypeClado= c(rep("", ColumnLenght)),
BGBeventTypeAnag= c(rep("", ColumnLenght))
)
counter = 1 # this counter will be used to populate the BSM_transitions table
# make a matrix to store lineages per area per time slice
CountStatesByTime_all_reps = matrix(NA, ncol = (length(statelabels)+4+num_areas), nrow = 0)
names_single_areas <- vector(length = num_areas)
for(i in 1:num_areas){names_single_areas[[i]] <- paste("SUM_",statelabels[[i+1]],sep="")}
colnames(CountStatesByTime_all_reps) = c("TimePoint","replication","BSM",statelabels, "LTT", names_single_areas)
# event names
n_insituesp <- "in_situ_speciation"
n_foundesp <- "founder_event_speciation"
n_vicsubsym <- "vicariance_or_subset_sympatry" # we will distinguish these events later by looking at both descendants
n_widesym_subsym <- "wide_sympatry_or_subset_sympatry" # we will distinguish these events later by looking at both descendants
n_vic <- "allopatry"
n_subsym <- "subset_sympatry"
n_dispersal <- "dispersal"
n_extinction <- "extinction"
n_disp_ext <- "dispersal_and_extinction"
n_impos_event <- "X"
no_event <- "–"
# make a matrix to store general statistics of the trees
transition_types <- c(n_insituesp, n_foundesp, n_vic, n_subsym, n_dispersal, n_extinction)
transition_types_mean <-lapply(transition_types, paste, "_mean", sep="")
transition_types_SD <-lapply(transition_types, paste, "_SD", sep="")
ReplicationParameters = matrix(0, ncol = 10+(2*length(transition_types)), nrow = n_trees)
colnames(ReplicationParameters) <- c("replication", "log-likelihood", "AICc", "k", "n_taxa", "d", "e", "j", "w", "treeHeight", transition_types_mean, transition_types_SD)
# make matrices to count the number of transitions between states
# template for event tables of each replication
state_by_state_transitions_template = matrix(0, ncol = length(statelabels), nrow = length(statelabels))
colnames(state_by_state_transitions_template) = statelabels
rownames(state_by_state_transitions_template) = statelabels
# a function by Liam Revell to get node numbers for descendants of a particular node. Thanks Liam!
getDescendants<-function(tree,node,curr=NULL){
if(is.null(curr)) curr<-vector()
daughters<-tree$edge[which(tree$edge[,1]==node),2]
curr<-c(curr,daughters)
w<-which(daughters>=length(tree$tip))
if(length(w)>0) for(i in 1:length(w))
curr<-getDescendants(tree,daughters[w[i]],curr)
return(curr)
}
#this will be important in case some of the trees have total age small enough to cross boundaries of the time slices
if (time_stratified) {
if(file.exists(paste(dir_name, "/modifier_matrices", sep= ""))==FALSE) dir.create(paste(dir_name, "/modifier_matrices", sep= ""))
#gets boundaries for time slices
time_slices <- scan(time_stratified_fn)
#get matrices to be modified
modifier_matrices <- c(dispersal_matrix_fn, area_adjacency_fn, distance_matrix_fn, areas_allowed_fn)
modifier_matrices <- modifier_matrices[modifier_matrices != ""]
#size of each matrix per time slice
n_lines_matrix <- 2+num_areas
#prepares modified matrices by successively removing the last time slice
for (t in 0:(length(time_slices)-1)){
for (i in 1:length(modifier_matrices)) {
write(c(readLines(modifier_matrices[i], n=(1+t)*n_lines_matrix),"END"),paste(dir_name, "/modifier_matrices/",t+1,"_",modifier_matrices[i], sep= ""))
}
reduced_time_slices <- head(time_slices, t+1)
cat(reduced_time_slices, file=paste(dir_name, "/modifier_matrices/",t+1,"_",time_stratified_fn,sep=""), sep = "\n")
}
}
################################
# set a BioGeoBEARS run object #
################################
# you should check this in detail but in most cases there is no need to change the parameters below
# defines an object, inputs trees and ranges, sets various parameters for the program
BioGeoBEARS_run_object = define_BioGeoBEARS_run() 					# Initialize a default model
BioGeoBEARS_run_object$geogfn = geogfn 								# Give BioGeoBEARS the location of the geography text file
BioGeoBEARS_run_object$max_range_size = max_range_size 				# Input the maximum range size
BioGeoBEARS_run_object$min_branchlength = 0.000001 					# Min to treat tip as a direct ancestor (no speciation event)
BioGeoBEARS_run_object$include_null_range = TRUE 					# set to FALSE for e.g. DEC* model, DEC*+J, etc.
BioGeoBEARS_run_object$on_NaN_error = -1e50 						# returns very low lnL if parameters produce NaN error (underflow check)
BioGeoBEARS_run_object$speedup = TRUE          						# shorcuts to speed ML search; use FALSE if worried (e.g. >3 params)
BioGeoBEARS_run_object$use_optimx = optimization  					# if FALSE, use optim() instead of optimx()
BioGeoBEARS_run_object$num_cores_to_use <- n_cores 					# use more cores to speed it up; this requires library(parallel) and/or library(snow)
BioGeoBEARS_run_object$force_sparse = FALSE
BioGeoBEARS_run_object$return_condlikes_table = TRUE 				# Good default settings to get ancestral states
BioGeoBEARS_run_object$calc_TTL_loglike_from_condlikes_table = TRUE # Good default settings to get ancestral states
BioGeoBEARS_run_object$calc_ancprobs = TRUE    						# get ancestral states from optim run
jmax = 2.99999														# max value for J parameter in DEC+J runs
# adds files with time slices, dispersal matrices, etc. if needed
if (time_stratified) {BioGeoBEARS_run_object$timesfn = time_stratified_fn}
if (areas_allowed) {BioGeoBEARS_run_object$areas_allowed_fn = areas_allowed_fn}
if (area_adjacency) {BioGeoBEARS_run_object$areas_adjacency_fn = area_adjacency_fn}
if (distance_matrix) {BioGeoBEARS_run_object$distsfn = distance_matrix_fn}
if (dispersal_matrix) {BioGeoBEARS_run_object$dispersal_multipliers_fn = dispersal_matrix_fn}
if (DIVALIKE){
jmax = 1.99999
# Set up DIVALIKE model
# Remove subset-sympatry
BioGeoBEARS_run_object$BioGeoBEARS_model_object@params_table["s","type"] = "fixed"
BioGeoBEARS_run_object$BioGeoBEARS_model_object@params_table["s","init"] = 0.0
BioGeoBEARS_run_object$BioGeoBEARS_model_object@params_table["s","est"] = 0.0
BioGeoBEARS_run_object$BioGeoBEARS_model_object@params_table["ysv","type"] = "2-j"
BioGeoBEARS_run_object$BioGeoBEARS_model_object@params_table["ys","type"] = "ysv*1/2"
BioGeoBEARS_run_object$BioGeoBEARS_model_object@params_table["y","type"] = "ysv*1/2"
BioGeoBEARS_run_object$BioGeoBEARS_model_object@params_table["v","type"] = "ysv*1/2"
# Allow classic, widespread vicariance; all events equiprobable
BioGeoBEARS_run_object$BioGeoBEARS_model_object@params_table["mx01v","type"] = "fixed"
BioGeoBEARS_run_object$BioGeoBEARS_model_object@params_table["mx01v","init"] = 0.5
BioGeoBEARS_run_object$BioGeoBEARS_model_object@params_table["mx01v","est"] = 0.5
}
if (BAYAREALIKE){
jmax = 0.99999
# Set up BAYAREALIKE model
# No subset sympatry
BioGeoBEARS_run_object$BioGeoBEARS_model_object@params_table["s","type"] = "fixed"
BioGeoBEARS_run_object$BioGeoBEARS_model_object@params_table["s","init"] = 0.0
BioGeoBEARS_run_object$BioGeoBEARS_model_object@params_table["s","est"] = 0.0
# No vicariance
BioGeoBEARS_run_object$BioGeoBEARS_model_object@params_table["v","type"] = "fixed"
BioGeoBEARS_run_object$BioGeoBEARS_model_object@params_table["v","init"] = 0.0
BioGeoBEARS_run_object$BioGeoBEARS_model_object@params_table["v","est"] = 0.0
# Adjust linkage between parameters
BioGeoBEARS_run_object$BioGeoBEARS_model_object@params_table["ysv","type"] = "1-j"
BioGeoBEARS_run_object$BioGeoBEARS_model_object@params_table["ys","type"] = "ysv*1/1"
BioGeoBEARS_run_object$BioGeoBEARS_model_object@params_table["y","type"] = "1-j"
# Only sympatric/range-copying (y) events allowed, and with exact copying (both descendants always the same size as the ancestor)
BioGeoBEARS_run_object$BioGeoBEARS_model_object@params_table["mx01y","type"] = "fixed"
BioGeoBEARS_run_object$BioGeoBEARS_model_object@params_table["mx01y","init"] = 0.9999
BioGeoBEARS_run_object$BioGeoBEARS_model_object@params_table["mx01y","est"] = 0.9999
}
if (J_founder_event){
BioGeoBEARS_run_object$BioGeoBEARS_model_object@params_table["j","type"] = "free"
BioGeoBEARS_run_object$BioGeoBEARS_model_object@params_table["j","init"] = 0.0001
BioGeoBEARS_run_object$BioGeoBEARS_model_object@params_table["j","est"] = 0.0001
BioGeoBEARS_run_object$BioGeoBEARS_model_object@params_table["j","min"] = 0.00001
BioGeoBEARS_run_object$BioGeoBEARS_model_object@params_table["j","max"] = jmax
}
#####################################################################################
# END OF OPTIONS BLOCK                     		                                    #
# the script should run completely from now on if everything above is set correctly #
#load packages
library(BioGeoBEARS)
library(rexpokit)
library(cladoRcpp)
#if you don't have BioGeoBEARS, install it from github (you need Rtools and devtools installed):
#install_github(repo="nmatzke/BioGeoBEARS")
scriptdir = np(system.file("extdata/a_scripts", package="BioGeoBEARS")) # BioGeoBEARS needs this
library(GenSA)
library(FD)
library(snow)
library(parallel)
library(ape)
library(phytools)
library(sjmisc)
library(tictoc)
library(tidyr)
library(RNeXML)
library(dplyr)
library(cladoRcpp)
#########################################
# create output directory and log file  #
#########################################
#sets working directory
wd = ("/Users/mac/Documents/PUBLICACIONES/PREPARACIÓN /1- BIOGEOGRAFIA DE ANTILLATTUS/BIOGEOBEAR/D2a")
setwd(wd)
getwd()
#analysis name to be appended to output files
trfn = "BIOGEOBEAR.tree"
moref(trfn)
tr = read.tree(trfn)
tr
plot(tr)
title("Example Clade Antillattus 2018 et al., Cala-Riquelme")
axisPhylo() # plots timescale
########################################################
# set inputs and some options for running the analyses #
########################################################
### RUN OPTIONS
#TRUE runs BioGeoBEARS to estimate ancestral ranges, FALSE loads previous runs
run_BGB = TRUE
#biogeographic stochastic mapping
# TRUE runs n_stochastic_maps biogeographic stochastic maps for each tree below;
# FALSE loads previous results
run_BSM =  TRUE
#number of BSM to run per tree
n_stochastic_maps = 10
#number of cores to be used in BioGeoBEARS likelihood estimations
n_cores <- 2
#method for searching for optimal parameters during ML calculations
#FALSE for optim, TRUE for optimx, "GenSA" for GenSA
optimization = TRUE
### TREES
#file with the posterior trees. This script assumes you have already discarded the pre-burn-in trees
#you can use the output of BEAST's LogCombiner directly
posterior_trees_fn <- "example_Sicarius_200_trees.nex"
#number of trees to be sampled from the posterior distribution
# set this to 1 only if you are providing a file with a single consensus / maximum clade credibility tree,
# or any other single, target tree
n_trees = 10
#sample_trees: TRUE samples n_trees from trees file, FALSE uses trees previously sampled and saved as /trees/tree1.nex, /trees/tree2.nex...
sample_trees = TRUE
#set fossil_tips to TRUE if your tree includes fossils as terminals; this will correct cases in which branch lengths are too short for BioGeoBEARS
fossil_tips = FALSE
### DISTRIBUTIONS
# name of the file containing the distributions
geogfn = "geog_BIO.txt"
# Look at the raw geography text file:
moref(geogfn)
# Look at your geographic range data:
tipranges = getranges_from_LagrangePHYLIP(lgdata_fn=geogfn)
tipranges
#gets the species names from the distribution file
#species without range data will be dropped from the trees later, so check this carefully!
species <- rownames(tipranges@df)
### COUNT EVENTS OPTIONS
# TRUE calculates SD for most common events (somewhat slow!)
get_SD_common_events = TRUE
# define the number of decimal digits for probabilities and ages in tables
n_digits_age <- 2
# define the size of the time slices to count lineages / area / time slice
time_period_size <- 1
# nodes of interest
# if you are interested in tracking the timing and transitions of particular nodes in the tree,
# define them here, and give names as you wish.
# all taxa belonging to each clade MUST be listed, because in some trees it might not be monophyletic
# this will tag the transitions table in 3 rows per node of interest (NoI):
# ancestor -> NoI, NoI -> daughter1, NoI -> daughter2
# if your nodes of interested are nested within each other, list them from most inclusive to less inclusive
nodes_of_interest <- list(
c("S_peruensis_506", "S_utriformis")
)
names(nodes_of_interest) <- c("Peru+Galapagos")
# defines outgroup; this is important if you want to include outgroups for ancestral range estimation
# but exclude them from the counts of transitions and lineages through time
# by default this script assumes your tree contains only the ingroup taxa
#leave this empty if your tree is represented solely by the ingroup
outgroup_taxa <- c()
### BIOGEOBEARS OPTIONS
# The script will run the DEC model by default. Set the parameters below to TRUE modify it
# Please not this script will run a single model each time, so do NOT set both DIVALIKE and BAYAREALIKE to TRUE simultaneously
DIVALIKE = TRUE
BAYAREALIKE = FALSE
J_founder_event = FALSE
#set these to TRUE and indicate the filenames for using dispersal matrices, time slices, etc.
time_stratified = TRUE
time_stratified_fn = "timeperiods.txt"
dispersal_matrix = FALSE
dispersal_matrix_fn = ""
area_adjacency = FALSE
area_adjacency_fn = ""
distance_matrix = FALSE
distance_matrix_fn = ""
areas_allowed = TRUE
areas_allowed_fn = "areas_allowed.txt"
# number of areas and maximum observed range size
areas = names(tipranges@df)
num_areas <- length(areas)
max_observed_range_size <- max(rowSums(dfnums_to_numeric(tipranges@df)))
# max range size (it can be equal to or higher than max_observed_range_size, but not lower)
max_range_size <- 3
# the total number of possible ranges depends both on the number of areas and max number of areas a species can occupy
# should be less than 1000 to run analysis in under a day, less than 1500 to run in under a week, less than 2500 to run at all
num_states <- numstates_from_numareas(numareas=num_areas, maxareas=max_range_size, include_null_range=TRUE)
### PLOTTING OPTIONS
#dimensions for the pdf output
pdf_w <- 10
pdf_h <- 15
#plot error intervals in graphic of lineages through time by area, or not
plot_95 = TRUE
#plot figures for individual stochastic maps; TRUE is slower and results in MANY files!
plot_BSM <- TRUE
# plot lineages through time by area or not
plot_LTT <- TRUE
# you can use n_maps_count_LTT to use only some of the maps for counting lineages through time
# this speeds things considerably
n_maps_count_LTT = 5
### saves a file with all the options for your reference
### perhaps it is a good idea to check this carefully before proceding to the next analyses
all_options <- c(filename, dir_name, run_BGB, sample_trees, run_BSM, n_stochastic_maps, plot_BSM, plot_LTT, n_maps_count_LTT, n_cores, optimization, posterior_trees_fn, n_trees, paste(outgroup_taxa, collapse=","), geogfn, n_digits_age, time_period_size, DIVALIKE, BAYAREALIKE, J_founder_event, time_stratified, time_stratified_fn, dispersal_matrix, dispersal_matrix_fn, area_adjacency, area_adjacency_fn, distance_matrix, distance_matrix_fn, areas_allowed, areas_allowed_fn, num_areas, max_observed_range_size, max_range_size, num_states, pdf_w, pdf_h)
options <- matrix(all_options, ncol = 1, nrow = length(all_options))
rownames(options) = c("filename", "dir_name", "run_BGB", "sample_trees", "run_BSM", "n_stochastic_maps", "plot_BSM", "plot_LTT", "n_maps_count_LTT", "n_cores", "optimx", "posterior_trees_fn", "n_trees", "outgroup_taxa", "geogfn", "n_digits_age", "time_period_size", "DIVALIKE", "BAYAREALIKE", "J_founder_event", "time_stratified", "time_stratified_fn", "dispersal_matrix", "dispersal_matrix_fn", "area_adjacency", "area_adjacency_fn", "distance_matrix", "distance_matrix_fn", "areas_allowed", "areas_allowed_fn", "num_areas", "max_observed_range_size", "max_range_size", "num_states", "pdf_w", "pdf_h")
write.table(options, file = paste(dir_name,"/analysis_options.txt",sep=""), col.names = F)
################################
# set a BioGeoBEARS run object #
################################
